/*
 * CGameStateMachine.cpp
 *
 *  Created on: Aug 31, 2011
 *      Author: welcome
 */
#include "CGameStateMachine.h"

namespace GGEngine {

CGameStateMachine::CGameStateMachine(CStateMachineDelegate* delegate) {
	this->stateCollection = new CStateCollection();
	this->currentState = KD_NULL;
	this->delegate = delegate;
}

CGameStateMachine::~CGameStateMachine() {
	if (stateCollection) {
		delete stateCollection;
		stateCollection = KD_NULL;
	}
}

KDboolean CGameStateMachine::activateStateWithID(int stateID) {
	if (stateCollection->stateCount() == 0)
		return KD_FALSE;

	CState *selectedState = getStateFromID(stateID);

	int prevStateName = currentState->getStateID();

	int actionID = selectedState->getActionID();

	KDboolean success = delegate->stateChangedFrom(prevStateName, stateID,
			actionID);

	if (success) {
		currentState = selectedState;
	}
	return success;
}
CState* CGameStateMachine::getStateFromID(int stateID) {
	int count = stateCollection->stateCount();

	vector<CState*> stateList = stateCollection->getStateList();

	for (int i = 0; i < count; i++) {
		CState *state = stateList[i];
		KDboolean equal = state->getStateID() == stateID ? KD_TRUE : KD_FALSE;
		if (equal) {
			return state;
		}
	}
	return KD_NULL;
}
KDboolean CGameStateMachine::activateFirstStateInList() {
	if (stateCollection->stateCount() == 0) {
		return KD_FALSE;
	}
	vector<CState*> stateList = stateCollection->getStateList();

	if (stateList.size() > 0) {

		CState *selectedState = stateList[0];

		if (selectedState) {

			int selectedStateID = selectedState->getStateID();

			int actionName = selectedState->getActionID();

			KDboolean success = delegate->stateChangedFrom(KD_NULL,
					selectedStateID, actionName);

			currentState = selectedState;

			return success;
		} else {
			return KD_FALSE;
		}
	} else {
		return KD_FALSE;
	}
}
void CGameStateMachine::updateWithEvents(set<int> events) {
	delegate->handleEvents(events);

	if (currentState) {
		CTrigger* selectedTrigger = KD_NULL;
		vector<CTrigger*> triggerList = currentState->getTriggerList();
		int triggerCnt = currentState->getTriggerCount();
		for (int i = 0; i < triggerCnt; i++) {
			CTrigger *trigger = triggerList[i];
			int eventID = trigger->getEventID();
			int matchEvent = 0;
			matchEvent = events.count(eventID);
			if (matchEvent > 0) {
				selectedTrigger = trigger;
				break;
			}
		}
		if (selectedTrigger) {
			int selectedStateID = selectedTrigger->getTargetStateID();
			if (!activateStateWithID(selectedStateID)) {
				activateFirstStateInList();
			}
		}
	}
}

} /* namespace GGE */
